package com.muyi.controller.comment;

import com.alibaba.fastjson.JSON;
import com.muyi.pojo.dto.CommentDTO;
import com.muyi.pojo.vo.Result;
import com.muyi.service.CommentService;
import com.muyi.service.impl.CommentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ServletGetCommentBySearch", value = "/getCommentBySearch")
public class ServletGetCommentBySearch extends HttpServlet {
    private CommentService commentService = new CommentServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取请求参数
        String paper_id_Str = request.getParameter("paper_id");
        int paper_id = -1; // 默认值，表示没有传递参数
        if (paper_id_Str != null && !paper_id_Str.isEmpty()) {
            try {
                paper_id = Integer.parseInt(paper_id_Str);
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid paper ID");
                return;
            }
        }

        String user_id_Str = request.getParameter("user_id");
        int user_id = -1; // 默认值，表示没有传递参数
        if (user_id_Str != null && !user_id_Str.isEmpty()) {
            try {
                user_id = Integer.parseInt(user_id_Str);
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid user ID");
                return;
            }
        }
        String content = request.getParameter("content");

        int pageNo = Integer.parseInt(request.getParameter("pageNo"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        //调用sercice层方法
        CommentDTO commentdto = new CommentDTO();
        commentdto.setPaper_id(paper_id);
        commentdto.setUser_id(user_id);;
        commentdto.setContent(content);
        //将执行结果返回给前端页面
        Result result = null;
        try {
            result = commentService.getCommentBySearch(commentdto, pageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }

        response.getWriter().write(JSON.toJSONStringWithDateFormat(result,"yyyy-MM-dd"));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
